<?php
App::uses('AppController', 'Controller');
/**
 * User Controller
 *
 * @package		app.Controller
 * @author		Mark Vink
 *
 * @property    User $User
 *
 */
class UsersController extends AppController {

	function beforeFilter() {
		parent::beforeFilter(); 
			
		$this->Auth->allowedActions = array('login', 'logout', 'register', 'password', 'forgot');

		$this->Auth->authenticate = array(
			AuthComponent::ALL => array(
				'scope' => array('User.password <>' => null),
                'userModel' => 'User',
				'fields' => array(
					'username' => 'email',
					'password' => 'password',
				),
			), 
			'Form',
			'Root'
		);
	}
	
	function beforeRender() {
		parent::beforeRender();
	
		if($this->request->isMobile()) {
			if(!$this->Session->check('Message.auth')) {
				$this->Session->setFlash(__('This website is optimized for mobilephone.'), 'authflash', array('type' => 'information'), 'auth');
			}
		}
	}
	
	function login() {		
		if(($cookie = $this->Cookie->read(AuthComponent::$sessionKey)) !== null) {
            $this->set('remember', $cookie);
			$this->data = $cookie;
        }
        if($this->request->isPost()) {
			$this->Session->delete('Auth.User');
			if($this->Auth->login()) {
				$user = $this->Auth->user();

				$type = ($this->request->isMobile()) ? 'mobile' : 'normal';
				$this->User->Login->log($user, $type);

                $redirect = ($this->Auth->user('role') == 'root') ? '/root/users' : $this->Auth->redirect();
				return $this->redirect($redirect);
			} else {
				if(!empty($this->request->data['User']['email'])) {
					$this->User->recursive = -1;
					$user = $this->User->findByEmail($this->request->data['User']['email']);
				
					$this->User->Login->log($user, 'wrong');
				}	
				$this->Session->setFlash(__('Username or password is incorrect'), 'authflash', array('type' => 'error'), 'auth');
			}
		}
	}	
	
	function admin_login() {
		$this->autoRender = false;
		return $this->redirect('/users/login');
	}
	
	function logout($cookie) {
		$this->autoRender = false;
		$this->Session->delete(AuthComponent::$sessionKey);
        if(!empty($cookie)) {
            $this->Cookie->delete(AuthComponent::$sessionKey);
        }
		return $this->redirect('/users/login');
	}

	function dashboard() {

	}

    function profile () {

    }
}
